# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import os

from conans import ConanFile, tools, CMake

required_conan_version = ">=1.42.0"


class FluentbitConan(ConanFile):
    name = "fluent-bit"
    license = "Apache License V2.0"
    generators = "cmake"
    description = "Fluent Bit is a fast Log, Metrics and Traces Processor and Forwarder"
    chost = None
    settings = "os", "compiler", "build_type", "arch"
    exports_sources = ["permissions.ini"]

    _cmake = None
    options = {
        "shared": [True, False]
    }
    default_options = {"shared": True}

    @property
    def _source_subfolder(self):
        return "source_subfolder"

    def source(self):
        git = tools.Git(verify_ssl=False)
        git.clone(**self.conan_data["sources"][self.version])

    def requirements(self):
        for require in self.conan_data["requires"][self.version]:
            self.requires(require)

    def build_requirements(self):
        for tool_require in self.conan_data["tool_requires"][self.version]:
            self.tool_requires(tool_require)

    def build(self):
        print("============= fluent-bit build begin =============")
        self.run("sed -i 's|\"${FLB_LIBYAML_DIR}/lib\"|\"${FLB_LIBYAML_DIR}/usr/lib64\"|g' CMakeLists.txt")
        cmake = self._configure_cmake()
        cmake.build()
        print("============= fluent-bit build end =============")

    def package(self):
        self.copy("libminiz.so.3", src="./lib", dst="usr/lib64", symlinks=True, keep_path=False)
        self.copy("libminiz.so.3.0.0", src="./lib", dst="usr/lib64", symlinks=True, keep_path=False)
        self.copy("fluent-bit", src="./bin", dst="bin", symlinks=True, keep_path=False)
        self.copy("permissions.ini", src="", dst="")

    def package_info(self):
        self.cpp_info.libdirs = ["usr/lib64"]
        self.cpp_info.libs = ["fluent-bit", "miniz"]
        self.cpp_info.includedirs = ["include"]
        self.env_info.LD_LIBRARY_PATH.append(
            os.path.join(self.package_folder, "usr/lib64")
        )

    def _configure_cmake(self):
        if self._cmake:
            return self._cmake
        self._cmake = CMake(self)

        # 传递bison环境变量给CMake
        bison_path = os.path.join(self.deps_env_info["bison"].path[0], "bison")
        self._cmake.definitions["BISON_EXECUTABLE"] = bison_path

        # 传递flex环境变量给CMake
        flex_path = os.path.join(self.deps_env_info["flex"].path[0], "flex")
        self._cmake.definitions["FLEX_EXECUTABLE"] = flex_path

        os.environ['CFLAGS'] = os.getenv('CFLAGS') + " -D_FORTIFY_SOURCE=2 -D_GNU_SOURCE -lm"
        os.environ['CXXFLAGS'] = os.getenv('CXXFLAGS') + " -D_FORTIFY_SOURCE=2 -D_GNU_SOURCE -lm"
        self._cmake.definitions["CMAKE_SKIP_RPATH"] = True
        self._cmake.definitions["BUILD_SHARED"] = self.options.shared

        sysroot = os.environ.get("CONAN_CMAKE_SYSROOT", default="")
        self._cmake.definitions["CMAKE_SYSROOT"] = sysroot

        self._cmake.definitions["FLB_MINIMAL"] = "Yes"
        self._cmake.definitions["FLB_IN_CPU"] = "Yes"
        self._cmake.definitions["FLB_IN_DUMMY"] = "Yes"
        self._cmake.definitions["FLB_IN_MEM"] = "Yes"
        self._cmake.definitions["FLB_IN_OPENTELEMETRY"] = "Yes"
        self._cmake.definitions["FLB_OUT_HTTP"] = "Yes"
        self._cmake.definitions["FLB_OUT_OPENTELEMETRY"] = "Yes"
        self._cmake.definitions["FLB_OUT_STDOUT"] = "Yes"

        self._cmake.definitions["FLB_WASM"] = "No"
        self._cmake.definitions["FLB_LUAJIT"] = "No"
        self._cmake.definitions["FLB_BACKTRACE"] = "No"
        lib_path = os.path.join(self.deps_cpp_info["libyaml"].rootpath)
        self._cmake.definitions["FLB_LIBYAML_DIR"] = lib_path
        self._cmake.definitions["FLB_WINDOWS_DEFAULTS"] = "No"
        self._cmake.definitions["FLB_PROXY_GO"] = "No"
        self._cmake.definitions["FLB_CUSTOM_CALYPTIA"] = "No"
        self._cmake.definitions["FLB_PREFER_SYSTEM_LIB_KAFKA"] = "No"
        self._cmake.definitions["FLB_EXAMPLES"] = "No"
        self._cmake.definitions["FLB_SQLDB"] = "No"
        self._cmake.definitions["FLB_REGEX"] = "No"

        if self.settings.arch == "armv8" or self.settings.arch == "x86_64":
            self._cmake.definitions["CMAKE_INSTALL_LIBDIR"] = "usr/lib64"
        else:
            self._cmake.definitions["CMAKE_INSTALL_LIBDIR"] = "usr/lib"
        self._cmake.configure(args=["--no-warn-unused-cli"])
        return self._cmake